/**
 * 数组转table
 * @param data 数组数据
 * @param td_style <td>标签的样式
 * @param tr_style <tr>标签的样式
 */
export default function array2table<T>(data: T[], td_style: string, tr_style: string) {
	if (!data || !Array.isArray(data)) {
		return '<table></table>';
	} else {
		const tr_style_str = tr_style ? ` style="${tr_style}"` : '';
		const td_style_str = td_style ? ` style="${td_style}"` : '';
		// get all fields
		const fields = Array.from(data.reduce((m, row) => {
			Object.keys(row).forEach((field) => {
				m.add(field);
			});
			return m;
		}, new Set<string>()));
		const tb = data.reduce((trs, row) => {
			const tds = fields.reduce((colums, field) => {
				const value = row[field] || '';
				if (Array.isArray(value)) {
					const sub_table = array2table(value, td_style, tr_style);
					colums.push(`<td${td_style_str}>${sub_table}</td>`);
				} else {
					colums.push(`<td${td_style_str}>${value}</td>`);
				}
				return colums;
			}, [] as string[]).join('');
			trs.push(`<tr${tr_style_str}>${tds}</tr>`);
			return trs;
		}, [] as string[]).join('');
		return `<table>${tb}</table>`;
	}
}
